package com.bana.fvs.webservice;

import com.bana.fvs.dao.StrategyDAO;
import com.bana.fvs.model.FogArea;
import com.bana.fvs.model.Strategy;
import com.bana.fvs.service.FogAreaService;
import com.bana.sys.utils.ActionResult;
import com.bana.sys.utils.Token;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * This class was generated by Apache CXF 3.1.18
 * 2019-06-06T22:46:30.001+08:00
 * Generated source version: 3.1.18
 * 
 */

@WebService(
                      serviceName = "GateWayServiceImplService",
                      portName = "GateWayServiceImplPort",
                      targetNamespace = "http://services.zhongan.com/",
                      endpointInterface = "com.bana.fvs.webservice.GateWayService")
@Service
public class GateWayServiceImplPortImpl implements GateWayService {

    private static final Logger LOG = Logger.getLogger(GateWayServiceImplPortImpl.class.getName());

    @Resource
    private FogAreaService fogAreaService;

    @Resource
    private StrategyDAO strategyDAO;

    /* (non-Javadoc)
     * @see com.bana.fvs.webservice.GateWayService#getVisibility(java.lang.String deviveNo)*
     */
    public java.lang.String getVisibility(java.lang.String deviveNo) { 
        LOG.info("Executing operation getVisibility");
        System.out.println(deviveNo);

        Document document=createDocument();

        try
        {
            FogArea fogArea=FogAreaService.FogAreaMap.get(Integer.parseInt(deviveNo));
            Element root=document.createElement("visibility");
            document.appendChild(root);
            if(fogArea!=null)
            {
                createVisibility(fogArea,document,root);
            }
        }
        catch (NumberFormatException ex)
        {
            createNumberErrorRoot(document);
        }
        return toXmlString(document);
    }

    /* (non-Javadoc)
     * @see com.bana.fvs.webservice.GateWayService#getCurrentFunction(java.lang.String deviveNo)*
     */
    public java.lang.String getCurrentFunction(java.lang.String deviveNo) { 
        LOG.info("Executing operation getCurrentFunction");
        System.out.println(deviveNo);
        Document document=createDocument();

        try
        {
            FogArea fogArea=FogAreaService.FogAreaMap.get(Integer.parseInt(deviveNo));
            Element root=document.createElement("function");
            document.appendChild(root);
            if(fogArea!=null)
            {
                createFunction(fogArea,document,root);
            }
            else
            {
                Element element1 = document.createElement("code");
                root.appendChild(element1);
                element1.setTextContent("12");
                Element element2 = document.createElement("message");
                root.appendChild(element2);
                element2.setTextContent("未找到设备");
            }
        }
        catch (NumberFormatException ex)
        {
            createNumberErrorRoot(document);
        }
        return toXmlString(document);
    }

    /* (non-Javadoc)
     * @see com.bana.fvs.webservice.GateWayService#isOnline(java.lang.String deviveNo)*
     */
    public java.lang.String isOnline(java.lang.String deviveNo) { 
        LOG.info("Executing operation isOnline");
        System.out.println(deviveNo);
        Document document=createDocument();

        try
        {
            FogArea fogArea=FogAreaService.FogAreaMap.get(Integer.parseInt(deviveNo));
            Element root=document.createElement("isOnline");
            document.appendChild(root);
            Element element1 = document.createElement("status");
            root.appendChild(element1);
            if(fogArea==null)
            {
                element1.setTextContent("0");
            }
            else
            {
                element1.setTextContent("1");
            }
        }
        catch (NumberFormatException ex)
        {
            createNumberErrorRoot(document);
        }
        return toXmlString(document);
    }

    /* (non-Javadoc)
     * @see com.bana.fvs.webservice.GateWayService#getGateWayStatus(java.lang.String deviveNo)*
     */
    public java.lang.String getGateWayStatus(java.lang.String deviveNo) {
        LOG.info("Executing operation getGateWayStatus");
        System.out.println(deviveNo);
        Document document=createDocument();

        try
        {
            FogArea fogArea=FogAreaService.FogAreaMap.get(Integer.parseInt(deviveNo));
            Element root=document.createElement("gateWayStatus");
            document.appendChild(root);
            if(fogArea!=null)
            {
                Element element1 = document.createElement("isOnline");
                root.appendChild(element1);
                Element element11 = document.createElement("status");
                element11.setTextContent("1");
                element1.appendChild(element11);

                Element element2 = document.createElement("function");
                root.appendChild(element2);
                createFunction(fogArea,document,element2);

                Element element3 = document.createElement("visibility");
                root.appendChild(element3);
                createVisibility(fogArea,document,element3);
            }
        }
        catch (NumberFormatException ex)
        {
            createNumberErrorRoot(document);
        }
        return toXmlString(document);
    }

    /* (non-Javadoc)
     * @see com.bana.fvs.webservice.GateWayService#sendFunction(java.lang.String deviveNo, java.lang.String funCode)*
     */
    public java.lang.String sendFunction(java.lang.String deviveNo, java.lang.String funCode) { 
        LOG.info("Executing operation sendFunction");

        Document document=createDocument();

        try
        {

            List<FogArea> fogAreas=fogAreaService.queryFogAreas(Token.SystemToken);
            FogArea currentFogArea=null;
            for (FogArea fogArea: fogAreas) {
                if(fogArea.getWqbm()==Integer.parseInt(deviveNo))
                {
                    currentFogArea=fogArea;
                    break;
                }
            }
            Element root=document.createElement("operateMsg");
            document.appendChild(root);
            Element element1 = document.createElement("code");
            root.appendChild(element1);
            Element element2 = document.createElement("message");
            root.appendChild(element2);
            if(currentFogArea==null)
            {
                element1.setTextContent("12");
                element2.setTextContent("未找到设备");
            }
            else
            {
                Strategy currentStrategy=strategyDAO.getStrategy(Integer.parseInt(funCode,16));

                if(currentStrategy==null)
                {
                    element1.setTextContent("13");
                    element2.setTextContent("未找到控制模式");
                }
                else
                {
                    currentFogArea.setCxsj("0");
                    currentFogArea.setGzms(2);
                    currentFogArea.setKzcl(currentStrategy.getClbm());
                    currentFogArea.setHdys(currentStrategy.getHdys());
                    currentFogArea.setHsjsdzsl(currentStrategy.getHsjsdzsl());
                    currentFogArea.setLdsc(currentStrategy.getLdsc());
                    currentFogArea.setMdsc(currentStrategy.getMdsc());
                    currentFogArea.setMqys(currentStrategy.getMqys());
                    currentFogArea.setSspl(currentStrategy.getSspl());
                    currentFogArea.setWdkz(currentStrategy.getWdkz());
                    currentFogArea.setWdld(currentStrategy.getWdld());
                    currentFogArea.setWdlddj(currentStrategy.getWdlddj());
                    currentFogArea.setZkb(currentStrategy.getZkb());
                    List<ActionResult> result=fogAreaService.setControllersConfig(Token.SystemToken,currentFogArea);
                    if(result.size()==0)
                    {
                        element1.setTextContent("0");
                        element2.setTextContent("操作成功");
                    }
                    else
                    {
                        int code=result.get(0).getCzjg();
                        element1.setTextContent(Integer.toString(code));
                        if(code==0)
                        {
                            element2.setTextContent("操作成功");
                        }
                        else if(code==1)
                        {
                            element2.setTextContent("与设备通信失败");
                        }
                        else if(code==2)
                        {
                            element2.setTextContent("与设备通信超时");
                        }
                        else if(code==3)
                        {
                            element2.setTextContent("连接失败");
                        }
                        else if(code==4)
                        {
                            element2.setTextContent("尚未连接");
                        }
                    }
                }
            }

        }
        catch (NumberFormatException ex)
        {
            createNumberErrorRoot(document);
        }
        catch (Exception ex)
        {
            createNumberErrorRoot(document);
        }
        return toXmlString(document);
    }

    private void createVisibility(FogArea fogArea, Document document, Element parent)
    {
        Element element = document.createElement("meters");
        element.setTextContent(String.valueOf(fogArea.getNjd()));
        parent.appendChild(element);
    }

    private void createFunction(FogArea fogArea,Document document,Element parent)
    {
        String funCode=Integer.toString(fogArea.getKzcl(),16);
        String kzclsm=fogArea.getKzclsm();
        Element element1 = document.createElement("funCode");
        element1.setTextContent(funCode);
        parent.appendChild(element1);
        Element element2 = document.createElement("funName");
        element2.setTextContent(kzclsm);
        parent.appendChild(element2);
        Element element3 = document.createElement("lightBright");
        element3.setTextContent(String.valueOf(fogArea.getWdld()));
        parent.appendChild(element3);
        Element element4 = document.createElement("lightFrequency");
        element4.setTextContent("0");
        parent.appendChild(element4);
        Element element5 = document.createElement("wakeLength");
        element5.setTextContent("0");
        parent.appendChild(element5);
        Element element6 = document.createElement("wakeTime");
        element6.setTextContent("0");
        parent.appendChild(element6);
        Element element7 = document.createElement("flowNum");
        element7.setTextContent("0");
        parent.appendChild(element7);
        Element element8 = document.createElement("flowSpeed");
        element8.setTextContent("0");
        parent.appendChild(element8);
        Element element9 = document.createElement("waveCrest");
        element9.setTextContent("0");
        parent.appendChild(element9);
        Element element10 = document.createElement("waveTrough");
        element10.setTextContent("0");
        parent.appendChild(element10);
        Element element11 = document.createElement("waveSpeed");
        element11.setTextContent("0");
        parent.appendChild(element11);
    }

    private void createNumberErrorRoot(Document document)
    {
        Element root=document.createElement("operateMsg");
        document.appendChild(root);
        Element element1 = document.createElement("code");
        element1.setTextContent("11");
        root.appendChild(element1);
        Element element2 = document.createElement("message");
        element2.setTextContent("不正确的数字格式");
        root.appendChild(element2);
    }

    private void createErrorRoot(Document document,Exception ex)
    {
        Element root=document.createElement("operateMsg");
        document.appendChild(root);
        Element element1 = document.createElement("code");
        element1.setTextContent("10");
        root.appendChild(element1);
        Element element2 = document.createElement("message");
        element2.setTextContent("系统异常");
        root.appendChild(element2);
    }

    private Document createDocument() {

        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  //创建DocumentBuilderFactory工厂对象
            DocumentBuilder builder  = factory.newDocumentBuilder();          //通过工厂对象, 创建DocumentBuilder制作对象
            Document document = builder.newDocument();                //通过制作对象, 创建一个Document对象,该对象代表一个XML文件
            document.setXmlStandalone(true);
            return document;
        }
        catch (ParserConfigurationException ex)
        {
            return null;
        }
    }

    private String toXmlString(Document document){

        try
        {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();

            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            String xml= bos.toString();
            bos.close();
            return new String(xml.getBytes(),"UTF8");
        }
        catch (TransformerException ex)
        {
            return null;
        }
        catch (IOException ex)
        {
            return null;
        }
    }
}
